package leetcode;

import org.junit.Test;

/**
 * @author: feiwang_6
 * @create: 2020/4/16 21:51
 * @description:
 */
public class ReversalNumber {

    @Test
    public void testMath(){
        System.out.println(reverseNum1(-12340));
        System.out.println(reverseNum2(-12340));
    }

    /**
     * 巧妙-临界值判断使用long型
     * @param source
     * @return
     */
    public int reverseNum1(int source){
        long rev = 0;
        int pop;
        while (source != 0){
            pop = source % 10;
            source = source / 10;
            rev = rev*10 + pop;
            if(rev > Integer.MAX_VALUE || rev < Integer.MIN_VALUE){
                return 0;
            }
        }
        return (int) rev;
    }

    public int reverseNum2(int source) {
        int rev = 0;
        int pop;
        int rMax = Integer.MAX_VALUE / 10;
        int maxFoot = Integer.MAX_VALUE % 10;
        int rMin = Integer.MIN_VALUE / 10;
        int minFoot = Integer.MIN_VALUE % 10;
        while (source != 0){
            pop = source % 10;
            source = source / 10;
            if(rev > rMax || (rev == rMax && pop > maxFoot)){
                return 0;
            }
            if(rev < rMin || (rev == rMin && pop < minFoot)){
                return 0;
            }
            rev = rev*10 + pop;
        }
        return rev;
    }
}
